package per.zx;

/**
 * @author zhengxin
 * @date 2021/6/30 21:31
 * @description 测试 ThreadLocal
 */
public class TestThreadLocal {

    // 创建一个 ThreadLocal
    static ThreadLocal<String> threadLocal1 = new InheritableThreadLocal<>();
    static ThreadLocal<String> threadLocal2 = new InheritableThreadLocal<>();

    public static void main(String[] args) {

        // 1.创建一个线程
        Thread a = new Thread(() -> {
            threadLocal1.set("A1");
            /*
                set方法：
                public void set(T value) {
                    //(1)获取当前线程
                    Thread t = Thread.currentThread();
                    //(2)获取当前线程的对应的ThreadLocalMap
                    ThreadLocalMap map = getMap(t);
                    //(3)判断获取到的map是否为null
                    if (map != null)
                        //(3.1)不是null，进行设值，注意，这个this指的是ThreadLocal变量，所以一个线程可以有多个ThreadLocal
                        map.set(this, value);
                    else
                        //(3.2)是null，先进行创建，再进行设值
                        createMap(t, value);
                }
                getMap方法：
                ThreadLocalMap getMap(Thread t) {
                    // 每个Thread都有一个域：ThreadLocal.ThreadLocalMap threadLocals = null;
                    return t.threadLocals;
                }
                createMap方法：
                void createMap(Thread t, T firstValue) {
                    // 给当前线程的threadLocals属性赋值，
                        // 注意不要被名字误导，这个不是ThreadLocal，而是ThreadLocal的内部类ThreadLocalMap
                    // 并且进行赋值
                    t.threadLocals = new ThreadLocalMap(this, firstValue);
                }

             */

            threadLocal2.set("A2");

            System.out.println(Thread.currentThread().getName()+" "+threadLocal1.get()); // thread-A A1
            System.out.println(Thread.currentThread().getName()+" "+threadLocal2.get()); // thread-A A2

        }, "thread-A");
        a.start();

        // 1.创建一个线程
        Thread b = new Thread(() -> {
            threadLocal1.set("B1");
            threadLocal2.set("B2");
            System.out.println(Thread.currentThread().getName()+" "+threadLocal1.get()); // thread-B B1
            System.out.println(Thread.currentThread().getName()+" "+threadLocal2.get()); // thread-B B2
        }, "thread-B");
        b.start();

    }


}
